<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>我的合同</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<!--数据与分页-->
<div class="contract_table_div">
    <!--多条件查询-->
    <div id="searchParam">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="name" class="layui-input" autocomplete="off" placeholder="合同名称">
            </div>
            <div class="layui-input-inline ">
                <button class="layui-btn" id="search">查询</button>
            </div>
        </div>
    </div>
    <!--显示数据的表格-->
    <table class="layui-hide" id="contract_table" lay-filter="contract_table"></table>
    <!--分页相关 View-->
    <div id="laypage" class="layui-laypage-btn"></div>
</div>


<!-- 新增编辑合同View-->
<div class="panel panel-default operation_contract" hidden>
    <div class="panel-heading title"></div>
    <div class="layui-card-body">
        <form class="layui-form" action="" lay-filter="deptInfo" style="width: 700px;margin-top: 10px">
            <input name="id" hidden/>
            <input name="papers" hidden>
            <input name='papersName' hidden>
            <div class="layui-form-item">
                <label class="layui-form-label">合同名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" placeholder="合同名称" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">房屋Id</label>
                <div class="layui-input-block">
                    <input type="text" name="houseId" placeholder="房屋" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">装修方案Id</label>
                <div class="layui-input-block">
                    <input type="text" name="decorationSchemeId" placeholder="装修方案" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存
                    </button>
                    <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
                </div>
            </div>
        </form>
    </div>
</div>

</body>
<script src="/layui/layui.js"></script>
<script src="/js/core.util.js"></script>
<!--新增合同按钮、批量删除 按钮-->
<script type="text/html" id="toolbar">
    <div class="layui-btn-group">
        <!--shiro:hasPermission="sys:contract:add"-->
        <button type="button" class="layui-btn" lay-event="addNewContract">
            <i class="layui-icon">&#xe608;</i> 新增合同
        </button>
    </div>
    <div class="layui-btn-group">
        <!--shiro:hasPermission="sys:contract:delete"-->
        <button type="button" class="layui-btn" lay-event="batchDeleted">
            <i class="layui-icon">&#xe608;</i> 批量删除
        </button>
    </div>
</script>
<!--给合同赋予角色按钮-->
<!--shiro:hasPermission="sys:contract:role:update"  shiro:hasPermission="sys:contract:update" shiro:hasPermission="sys:contract:delete" -->
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>

    layui.use(['jquery', 'form', 'table', 'laypage', 'layer', 'upload'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var laypage = layui.laypage
        var layer = layui.layer;
        var upload = layui.upload;

        /*分页查询条件*/
        let searchParam = {
            current: 1,
            size: 10,
            /*以下为多条件查询参数*/
            name: null,
        }

        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });
        });

        /**
         * 渲染上传文件组件
         */
        upload.render({
            elem: '#papers'
            , accept: 'file' // 允许上上传各种文件
            , url: '/upload'
            , done: function (res) {
                layer.msg('上传成功');
                setPapersValue(res.data.src, res.data.title)
            }
        });

        /**
         * 设置上传的文件
         * @param src 上传的文件路径
         * @param papersName 文件名
         */
        let setPapersValue = function (src, papersName) {
            if (papersName !== undefined) {
                layui.$('#uploadDemoView').find('ul').append(`<li  style="display: flex;align-content: center">${papersName}<i class="layui-icon file"></i></li>`)
                $("input[name=papersName]").val(papersName)
            }
            $("input[name=papers]").val(src)
            $(".file").on("click",function (even) {
                $("input[name=papersName]").val("")
                $("input[name=papers]").val("")
                $(even.target).parent().remove()
                layer.msg("移除成功")
                return false
            })
        }


        /**
         *  加载分页数据
         */
        function loadPageInfo() {
            CoreUtil.sendAjax("/zx/contract/page/user", searchParam, function (res) {
                //初始化分页器
                laypageTable(res.total, searchParam.current);
                //初始化渲染数据
                loadTable(res.records);
                if (res.records != null) {
                    loadTable(res.records);
                }
            }, "GET", false, function (res) {
                //用户列表接口无权限回调
                layer.msg("抱歉！您暂无获取用户列表的权限");
                let noAuthorityData;
                noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        }


        $("#search").click(function () {
            searchParam.name = $("#name").val();
            searchParam.current = 1;
            loadPageInfo();
        });

        //渲染分页插件
        var laypageTable = function (count, currentPage) {
            laypage.render({
                elem: 'laypage'
                , count: count
                , limit: searchParam.size
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                , curr: location.hash.replace('#!currentPage=', '')     //获取起始页
                , hash: 'currentPage'                                   //自定义hash值
                , jump: function (obj, first) {
                    if (!first) {
                        searchParam.current = obj.curr;
                        searchParam.size = obj.limit;
                        loadPageInfo();
                    }
                }
            });
        };
        //渲染table
        var loadTable = function (data) {
            //展示已知数据
            table.render({
                elem: '#contract_table'
                // 这个 data 为数组数据，直接 放到 data 上即可。
                , data: data
                , even: true
                , limit: data.length
                , limits: [10, 20, 30, 40, 50]
                , toolbar: '#toolbar'
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', width: 20, sort: true},
                        {field: 'name', title: '合同名称', width: 230},
                        {
                            field: "status", title: "状态", width: 200, templet: generateSwitch
                        },
                        {
                            field: "signatory", title: "签订人", width: 300
                        },
                        {
                            field: "houseId", title: "房屋Id", width: 300
                        },
                        {
                            field: "decorationSchemeId", title: "装修方案Id", width: 300
                        },
                        {
                            title: "合同文件", width: 300, templet: function (item) {
                                return `<a href=${"'"+item.papers+"'"}>${item.papersName}</a>`
                            }
                        },
                        {width: 300, toolbar: "#tool", title: '操作'}
                    ]
                ]
            });
        };
        loadPageInfo();

        //点击新增事件， 表头工具栏事件
        table.on('toolbar(contract_table)', function (obj) {
            switch (obj.event) {
                case 'addNewContract':
                    $(".title").html("新增合同");
                    $(".contract_table_div").hide();
                    $(".operation_contract").show();
                    $(".operation_contract input[name=id]").val("");
                    $(".operation_contract input[name=name]").val("");
                    // 清理文件上传信息
                    $(".operation_contract input[name=papers]").val("");
                    $(".operation_contract input[name=papersName]").val("");
                    // 签订人重置
                    $(".operation_contract input[name=signatory]").val("")
                    $(".operation_contract input[name=houseId]").val("")
                    $(".operation_contract input[name=decorationSchemeId]").val("")
                    form.render(); //更新全部
                    break;
                case 'batchDeleted':
                    let checkStatus = table.checkStatus(obj.config.id);
                    let data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg("请选择要批量删除的合同");
                    } else {
                        let contractIds = [];
                        $(data).each(function (index, item) {
                            contractIds.push(item.id);
                        });
                        tipDialog(contractIds, "选中的");
                    }
                    break;
            }
        });

        //编辑或新增的界面取消事件
        $("#btn_cancel").click(function () {
            //显示表格
            $(".contract_table_div").show();
            //隐藏编辑窗口
            $(".operation_contract").hide();
            //可以防止在表单事件操作后自动刷新
            return false;
        });

        //监听提交 新增和编辑  保存按钮
        form.on('submit(submit)', function (data) {
            data.field.status = getStatus(data.field)
            //新增
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendAjax("/zx/contract/user", JSON.stringify(data.field), function (res) {
                    //显示表格
                    loadPageInfo();
                    $(".contract_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_contract").hide();
                    // 刷新页面，但是不管事儿
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //新增合同无权限提示
                    layer.msg("抱歉！您暂无新增合同的权限");
                });
                // 编辑
            } else {
                CoreUtil.sendAjax("/zx/contract/user", JSON.stringify(data.field), function (res) {
                    //显示表格
                    $(".contract_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_contract").hide();
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //更新合同无权限提示
                    layer.msg("抱歉！您暂无编辑合同的权限");
                });
            }
            return false;
        });


        //执行查询
        $("#search").click(function () {
            searchParam.title = $("#name").val();
            searchParam.current = 1;
            loadPageInfo();
        });


        // 操作工具栏 点击赋予角色事件事件
        table.on('tool(contract_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'edit':
                    $(".contract_table_div").hide();
                    $(".operation_contract").show();
                    $(".title").html("编辑合同");
                    $(".operation_contract input[name=id]").val(data.id);
                    $(".operation_contract input[name=name]").val(data.name);
                    let statusElement = $(".operation_contract input[name=status]");
                    // 回显状态
                    setStatus(statusElement, data.status)
                    // 清理文件上传信息
                    setPapersValue(data.papers, data.papersName)
                    // 签订人重置
                    $(".operation_contract input[name=signatory]").val(data.signatory)
                    $("input[name=houseId]").val(data.houseId)
                    $("input[name=decorationSchemeId]").val(data.decorationSchemeId)
                    form.render(); //更新全部
                    break;
                case 'del':
                    var contractIds = [];
                    contractIds.push(data.id);
                    tipDialog(contractIds, data.name);
                    break;
            }
        });

        /**
         * 通过状态获取状态值
         */
        let getStatus = function (data) {
            let status = data.status;
            return status === 'on' ? 1 : 0;
        }

        /**
         * 设置表单中的状态
         */
        let setStatus = function (element, status) {
            if (status === 1) {
                $(element).attr("checked", "checked")
            } else {
                $(element).removeAttr("checked")
            }
        }

        /**
         * 更具状态值获取状态
         */
        let generateSwitch = function (data) {
            let status = data.status;
            return status === 1 ? "开启" : "草稿";
        }

        //删除前确认对话框
        var tipDialog = function (contractIds, name) {
            layer.open({
                content: '确定要删除' + name + "合同么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendAjax("/zx/contract", JSON.stringify(contractIds), function (res) {
                        layer.msg(res.message);
                        $(".layui-laypage-btn").click();
                    }, "DELETE", false, function (res) {
                        //删除合同无权限
                        layer.msg("抱歉！您暂无删除合同的权限");
                    });
                }
            });
        };
    });
</script>
</html>

